package com.can.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.can.constant.SystemConstants;
import com.can.domain.entity.Menu;
import com.can.domain.entity.RoleMenu;
import com.can.domain.vo.MenuTreeVO;
import com.can.enums.AppHttpCodeEnum;
import com.can.exception.SystemException;
import com.can.mapper.MenuMapper;
import com.can.service.MenuService;
import com.can.service.RoleMenuService;
import com.can.util.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限表(SysMenu) 服务实现类
 *
 * @author cancan
 * @since 2023-05-11 10:16:02
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private RoleMenuService roleMenuService;

    @Override
    public List<String> selectPermsByUserId(Long id) {
        //如果是管理员，返回所有的权限
        if (id == 1L) {
            LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(Menu::getMenuType, SystemConstants.MENU, SystemConstants.BUTTON);
            wrapper.eq(Menu::getStatus, SystemConstants.STATUS_NORMAL);
            List<Menu> menus = list(wrapper);
            List<String> perms = menus.stream()
                    .map(Menu::getPerms)
                    .collect(Collectors.toList());
            return perms;
        }
        //否则返回所具有的权限
        return getBaseMapper().selectPermsByUserId(id);
    }

    @Override
    public void update(Menu menu) {
        if (menu.getId().equals(menu.getParentId())) {
            throw new SystemException(AppHttpCodeEnum.PARENTID_FAIL);
        }
        updateById(menu);
    }

    @Override
    public void delete(Long menuId) {
        List<Menu> menus = list(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, menuId));
        if (!ObjectUtils.isEmpty(menus)) {
            throw new SystemException(AppHttpCodeEnum.EXIT_SON);
        }
        removeById(menuId);
    }

    @Override
    public List<Menu> selectRouterMenuTreeByUserId(Long userId) {
        MenuMapper menuMapper = getBaseMapper();
        List<Menu> menus = null;
        //判断是否是管理员
        if (SecurityUtils.isAdmin()) {
            //如果是 获取所有符合要求的Menu
            menus = menuMapper.selectAllRouterMenu();
        } else {
            //否则  获取当前用户所具有的Menu
            menus = menuMapper.selectRouterMenuTreeByUserId(userId);
        }

        //构建tree
        return getChildren(new Menu().setId(0L), menus);
    }

    @Override
    public List<Menu> selectRouterMenuTreeAll() {
        List<Menu> menus = getBaseMapper().selectAllRouterMenu();
        // 前端需要label字段
        menus.stream().forEach(menu -> menu.setLabel(menu.getMenuName()));
        return getChildren(new Menu().setId(0L), menus);
    }

    @Override
    public MenuTreeVO selectRouterMenuTreeByRoleId(Long id) {
        MenuTreeVO menuTreeVO = new MenuTreeVO();
        menuTreeVO.setMenus(selectRouterMenuTreeAll());

        List<RoleMenu> roleMenuList = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, id));
        List<Long> menuIds = roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        menuTreeVO.setCheckedKeys(menuIds);

        return menuTreeVO;
    }


    /**
     * 获取存入参数的 子Menu集合
     *
     * @param menu
     * @param menus
     * @return
     */
    private List<Menu> getChildren(Menu menu, List<Menu> menus) {
        List<Menu> childrenList = menus.stream()
                .filter(m -> m.getParentId().equals(menu.getId()))
                .map(m -> m.setChildren(getChildren(m, menus)))
                .collect(Collectors.toList());
        return childrenList;
    }

}

